/*                                                                            
  Copyright (c) 2014-2015, GoBelieve     
    All rights reserved.		    				     			
 
  This source code is licensed under the BSD-style license found in the
  LICENSE file in the root directory of this source tree. An additional grant
  of patent rights can be found in the PATENTS file in the same directory.
*/

#import "UtilFileCache.h"
#import <CommonCrypto/CommonDigest.h>

@interface UtilFileCache()
@property(nonatomic)NSString *cachePath;
@end

@implementation UtilFileCache

+ (instancetype)instance {
    static UtilFileCache *m;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (!m) {
            m = [[UtilFileCache alloc] init];
        }
    });
    return m;
}

- (instancetype)init{
    self = [super init];
    if (self) {
        self.fileManager = [[NSFileManager alloc] init];
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
        self.cachePath = [paths[0] stringByAppendingPathComponent:@"file_cache"];
        if (![self.fileManager fileExistsAtPath:self.cachePath]) {
              [self.fileManager createDirectoryAtPath:self.cachePath withIntermediateDirectories:YES attributes:nil error:NULL];
        }
    }
    return self;
}

- (NSString *)cachePathForKey:(NSString *)key inPath:(NSString *)path {
    NSString *filename = [self cachedFileNameForKey:key];
    return [path stringByAppendingPathComponent:filename];
}

- (NSString *)defaultCachePathForKey:(NSString *)key {
    return [self cachePathForKey:key inPath:self.cachePath];
}

-(NSString*)cachePathForKey:(NSString*)key {
    NSString *extension = [key pathExtension];
    NSString *appendingName = @"";
    if (extension.length > 0) {
        appendingName = [NSString stringWithFormat:@".%@", extension];
    }
    return [self cachePathForKey:key withAppendingName:appendingName];
}

-(NSString*)cachePathForKey:(NSString*)key withAppendingName:(NSString *)appendingName {
    return [[self cachePathForKey:key inPath:self.cachePath] stringByAppendingString:appendingName];
}

- (NSString *)cachedFileNameForKey:(NSString *)key
{
    const char *str = [key UTF8String];
    if (str == NULL)
    {
        str = "";
    }
    unsigned char r[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (CC_LONG)strlen(str), r);
    NSString *filename = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                          r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], r[15]];
    
    return filename;
}

-(void)storeFile:(NSData*)data forKey:(NSString*)key withAppendingName:(NSString *)appendingName {
    [self.fileManager createFileAtPath:[[self defaultCachePathForKey:key] stringByAppendingString:appendingName] contents:data attributes:nil];
}

-(void)storeFile:(NSData*)data forKey:(NSString*)key {
    //[self.fileManager createFileAtPath:[self defaultCachePathForKey:key] contents:data attributes:nil];
    NSString *extension = [key pathExtension];
    NSString *appendingName = @"";
    if (extension.length > 0) {
        appendingName = [NSString stringWithFormat:@".%@", extension];
    }
    [self storeFile:data forKey:key withAppendingName:appendingName];
}

-(void)removeFileForKey:(NSString*)key {
    NSString *extension = [key pathExtension];
    NSString *appendingName = @"";
    if (extension.length > 0) {
        appendingName = [NSString stringWithFormat:@".%@", extension];
    }
    [self removeFileForKey:key withAppendingName:appendingName];
}

-(void)removeFileForKey:(NSString*)key withAppendingName:(NSString *)appendingName {
    [self.fileManager removeItemAtPath:[[self defaultCachePathForKey:key] stringByAppendingString:appendingName] error:nil];
}

-(NSString*)queryCacheForKey:(NSString*)key {
    NSString *extension = [key pathExtension];
    NSString *appendingName = @"";
    if (extension.length > 0) {
        appendingName = [NSString stringWithFormat:@".%@", extension];
    }
    return [self queryCacheForKey:key withAppendingName:appendingName];
}

-(NSString*)queryCacheForKey:(NSString*)key withAppendingName:(NSString *)appendingName {
    NSString *cachePath = [[self defaultCachePathForKey:key] stringByAppendingString:appendingName];
    if ([self.fileManager fileExistsAtPath:cachePath]) {
        return cachePath;
    } else {
        return nil;
    }
}

@end
